#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
#include <ip2c.h>

#define IP_LISTCOUNT 1

char *ip2c_long2ip(const unsigned long ip_long)
{
	return (char *)inet_ntoa(ntohl(ip_long));
}

unsigned long ip2c_ip2long(const char *ip_char)
{
	unsigned long ip = inet_addr(ip_char);

	return ntohl(ip);
}

int main(int argc, char *argv[])
{
	unsigned long iplist;
	struct ip2c_db *db;
	ip2c_country_code *iso_codes = NULL;

	if(argc != 2)
	{
		printf("Usage: %s <ip>\n", argv[0]);
		return -1;
	}

	iplist = ip2c_ip2long(argv[1]);
	printf("%s=%lu\n", argv[1], iplist);

	if((iso_codes = malloc(sizeof(ip2c_country_code))) == NULL)
	{
		fprintf(stderr, "Erorr: cannot allocate memory!\n");
		return -1;
	}

	db = (struct ip2c_db *)ip2c_db_init();
	if(ip2c_db_load(db, "/etc/ip2c-latest.db") != 0)
	{
		return -1;
		ip2c_db_free(db);
	}
//	ip2c_db_version(db);
	ip2c_getcountry(db, &iplist, 1, iso_codes);
//	ip2c_getcountry(db, &iplist, 2, iso_codes);
	ip2c_db_free(db);

	if(iso_codes[0])
	{
		printf("%s\t - FOUND(%s)\n", ip2c_long2ip(iplist), iso_codes[0]);
	} else {
		printf("%s\t - MISS!\n", ip2c_long2ip(iplist));
	}

	return 0;
}
